var express = require('express');
var router = express.Router();
var merModel = require('../models/mer-model');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var db = merModel.merchant;

router.get('/', function (req, res, next) {
    res.render('updatemer', { title: 'Express' });
});

router.put('/update/:id', function (req, res) {
    db.findOneAndUpdate({ '_id': req.params.id }, req.body, function (err, data) {
        if (err) {
            console.log('UPDATE MERCHANT ERROR' + err);
        }
        else {
            res.send(data);
        }
    });
});

router.post('/register', function (req, res) {
    db.findOne({ 'merchant_name': req.body.merchant_name }, function (err, data) {
        if (err) {
            db.collection.insert(req.body, function (err) {
                if (err) {
                    console.log('INSERT ERROR ' + err);
                }
                else {
                    res.send(200, "Register Successfully");        
                }
            });
        }
        else {
            res.send(404, "Duplicate Username");
        }
    });
});

router.post('/login', function (req, res) {
    db.findOne({ 'merchant_name': req.body.merchant_name, 'password': req.body.password }, function (err, data) {
        if (err) {
            res.send(404);
        }
        else {
            //登录成功，存session
            req.session.merchant = data;
            // console.log(req.session.merchant);
            res.send(200, 'login success');
        }
    });
});

router.get('/logout', function (req, res) {
    req.session.destroy(function (err) {
        if (err) {
            res.send('Server Error,logout fail');
        }
        else {
            res.send(200, 'logout success');
            console.log(req.session.merchant);
        }
    });
});

// 获取所有merchant 
router.get('/merchant', function (req, res) {
    db.find({}, {password : 0}, function (err, docs) {
        if (err) {
            console.log("FIND ERROR", err);
        } else {
            res.send(docs);
        }
    });
});

// 获取指定id 的merchant 
router.get('/merchant/:mId', function (req, res) {
    var mId = req.params.mId;
    db.findOne({ '_id': mId }, {password : 0}, function (err, data) {
        if (err) {
            res.send(404);
        }
        else {
            res.send(data);
        }
    });
});


module.exports = router;